
/**************************** Display Photo Albums*********************************/

function displayPhotos(albumId, userName, resultDiv, albumName) {
    //alert("albumId: " + albumId);
    //alert("user name: " + userName);
    //alert("resultDiv: " + resultDiv);
    i_albumid = albumId;
	s_username = userName;
    if ($('#isSortting').val() == "true") {
        return false;
    }
    var btnAddPhotos = document.getElementById("btnAddNewPhotos");
    btnAddPhotos.onclick = function() {
        openPopup_click('UploaderDiv', 800, albumId, userName, resultDiv, albumName);
        isCreatingAlbum = false;
    };
    var url = "fetchPhotos.asp" + "?cat1=" + albumId + "&cat2=" + userName + "&random=" + Math.random(); 
    
    $.ajax({
            type: "POST",
            url: url,
            dataType: "text",
            cache: false,
            error: function(XMLHttpRequest, textStatus, errorThrown) {
                alert(textStatus);
            },
            complete: function(response) {
                callbackPhotos(response)
            }
        });
    $('#albumName').val(albumName);
    $('#btRenameAlbum').unbind('click');
    $('#btRenameAlbum').click(function () {
        

        var newAlbumName = $('#albumName').val();
        if (newAlbumName.length == 0) {
            $('#msgRename').text('Album name is invalid!').css('display', 'block').delay(3000).fadeOut(500);
            return false;
        }
        $.ajax({
            type: "POST",
            url: "updateAlbum.asp",
            data: { id: albumId, action: 1, name: newAlbumName },
            dataType: "text",
            error: function (XMLHttpRequest, textStatus, errorThrown) {
                alert(textStatus);
            },
            complete: function (response) {
                $('#albumInfo' + albumId).html(newAlbumName);
                $('#album' + albumId).removeAttr('onmouseup');
                $('#album' + albumId).unbind('mouseup');
                $('#album' + albumId).mouseup(function () {
                    displayPhotos(albumId, userName, 'photoDiv', newAlbumName);
                });
                $('#msgRename').text('Renamed successfully!').css('display', 'block').delay(3000).fadeOut(500);
            }
        });
    });  
}

function getHTTPRequestObject() {
    try {
        // Try legacy object first
        xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
    }
    catch (e) {
        try {
            // Try IE implementation now
            xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
        }
        catch (E) {
            xmlhttp = false;
        }
    }
    if (!xmlhttp && typeof XMLHttpRequest != 'undefined') {
        // We must be using a Mozilla-based browser
        // so create a native request object now
        xmlhttp = new XMLHttpRequest();
    }
}

function callbackPhotos(response) {

    var strResponseText = "";
    strResponseText = response.responseText;
            //alert(strResponseText);            
            var endIndex = (strResponseText.indexOf("@"));
            var strPhotos = strResponseText.substr(0, endIndex);
            //alert("strPhotos = " + strPhotos);
			$("#photosContainer").remove();
            if (strPhotos == "not found") {
                //alert("Your photo search is not found!");
                //return false;
            }
            else {
                
                strResponseText = strResponseText.substr(0, endIndex);
                //alert(strResponseText);
                if (strResponseText != "") {
                    eval("var objResults = " + strResponseText);
                    var divResults = document.getElementById("photoDiv");
                    //if (document.getElementById("photoDiv")) { $("#photosContainer").remove(); }
                    
                    var photoRow, photoCell;
                    var ul = document.createElement("ul");
                    var strFileName = "";
                    var strThumbFileName = "";
                    var count = objResults.Results.records.length;
                    var j = 0;
                    var divWidth = 0;

                    ul.id = "photosContainer";
                    // loop through each of the rows in the result
                    var iPhotoId = 0;
                    var strUserName = "";
                    var strFileName = "";
                    var strTitle = "";
                    var strDescription = "";
                    var strDateTaken = "";
                    var iAlbumID = 0;
                    for (var i = 0; i < count; i++) {
                        iPhotoId = objResults.Results.records[i].photoID;
                        strUserName = objResults.Results.records[i].username;
                        strFileName = objResults.Results.records[i].fileName;
                        strTitle = objResults.Results.records[i].title;
                        strDescription = objResults.Results.records[i].description;
                        strDateTaken = objResults.Results.records[i].dateTaken;
                        iAlbumID = objResults.Results.records[i].albumID;

                        // we'll create each photo row
                        photoRow = document.createElement("li");
                        photoRow.id = "photo" + iPhotoId;
                        photoRow.setAttribute("onmouseup", "edit(" + iPhotoId + ",'" + strTitle + "','" + strDescription + "','" + strDateTaken + "'," + iAlbumID + ")");
                        /*
                        $('#photo' + id).mouseup(function() {
                            edit(iPhotoId, strTitle, strDescription, strDateTaken);
                        });
                        */

                        var imageNode = document.createElement("div");
                        imageNode.setAttribute("class", "image-holder");
                        strThumbFileName = "photos/" + strUserName + "/Thumbnails/" + strFileName;
                        strFileName = "photos/" + strUserName + "/" + strFileName;
                        var img = document.createElement("img");
                        img.setAttribute("src", strThumbFileName);
                        
                        imageNode.appendChild(img)
                        photoRow.appendChild(imageNode);
                        $(imageNode).append('<div class="viewPhotoContainer"><a class="view-photo" href="' + strFileName + '">View Photo</a></div>');

                        var node = document.createElement("span");
                        node.id = "info" + iPhotoId;
                        //var textNode = document.createTextNode("Title: " + strTitle + "  Description:  " + strDescription + "  Date taken: " + strDateTaken);
                        var textNode = document.createTextNode(strTitle);
                        node.appendChild(textNode);
                        photoRow.appendChild(node);
                        
                        var editContainer = document.createElement("div")
                        editContainer.id = "edit-container" + iPhotoId;
                        editContainer.setAttribute("class", "edit-container");
                        photoRow.appendChild(editContainer);
                         
                        ul.appendChild(photoRow);
                    }
                    
                    // add the table to the div tag
                    divResults.appendChild(ul);
                    if (count > 0) {
                        
                        $("#photosContainer").sortable({
                            cursor: 'move',
                            start: function(event, ui) { $('#isSortting').val('true'); },
                            stop: function(event, ui) {
                                $('#isSortting').val('false');
                                if (confirm("Do you want to save sort order?")) {
                                    saveOrder('photo');
                                } else {
                                    $(this).sortable('cancel');
                                }
                            }
                        });
                        $('.viewPhotoContainer a').lightBox();
                    }
					
                }
            } 
			$("#menu").tabs("select", 1);			
}


/********************** end of displaying photos function ********************/
var lastEditId = 0;
var lastTitle;
var lastDescription;
var lastDateTaken;
function edit(id, title, description, dateTaken, albumId ) {

    if ($('#isSortting').val() == "true") {
        return false;
    }
//    $("#photosContainer").sortable("destroy");
    if (lastEditId > 0 && lastEditId != id) {
        cancelEdit(lastEditId, lastTitle, lastDescription, dateTaken);
    }
    lastEditId = id;
    lastTitle = title;
    lastDescription = description;
    lastDateTaken = dateTaken;

    var container = $('#edit-container' + id);
    $('#photo' + id).removeAttr('onmouseup');
    $('#photo' + id).unbind('mouseup');

    var divCaption = $(document.createElement('div'));
    divCaption.addClass('caption')
		              .append('<label for="caption">Caption:</label>')
		              .append('<textarea id="caption" onfocus="this.value = this.value;" name="caption" cols="30" rows="8">' + description + '</textarea>');

    var divTitle = $(document.createElement('div'));
    divTitle.addClass('title')
		            .append('<label for="Title">Title:</label>')
		            .append('<input type="text" id="title" name="Title" value="' + title + '"/>');

    var divDate = $(document.createElement('div'));
    divDate.addClass('date')
		           .append('<label for="dateTaken">Date:</label>')
		           .append('<input type="text" id="dateTaken" name="dateTaken" value="' + dateTaken + '" class="date" />');

    var divSelect = $(document.createElement('div'));
    divSelect.addClass('albums-select')
    var selectTag = $('#albumsCombobox'); 
    divSelect.append(selectTag);

    var divButton = $(document.createElement('div'));
	var imgName = $('#photo' + id + ' > div > img').attr('src');
	var cancelEditEvent = "cancelEdit(" + id + ",'" + title + "','" + description + "','" + dateTaken + "'," + albumId + ")";
    var savePhotoEvent = "savePhoto(" + id + "," + albumId + ")";
    var deletePhotoEvent = "deletePhoto(" + id + ",'" + imgName + "'," + albumId + ")";
    divButton.addClass('button-container')
                     .append('<input type="button" class="button" id="delete" onclick="' + deletePhotoEvent  + '"value="delete"/>')
		             .append('<input type="button" class="button" id="save" onclick="' + savePhotoEvent + '" value="save"/>')
		             .append('<input type="button" class="button" onclick="' + cancelEditEvent + '" value="cancel"/>');
    $('#photo' + id).addClass('active');
    $('#edit-container' + id).html(divCaption)
		                        .append(divTitle)
		                        .append(divDate)
		                        .append(divSelect)
		                        .append(divButton).show();
	$('#info'+id).hide();	                        
    $('#caption').focus();
    $("#photosContainer").sortable("disable");

}
function cancelEdit(id, title, description, dateTaken, albumId) {
    $('#variable').append($('#albumsCombobox'));
    $('#albumsCombobox').val("");
    $('#edit-container' + id).html("");
    $('#photo' + id).mouseup(function() {
        edit(id, title, description, dateTaken, albumId);
    });
    $('#info' + id).show();    
    $('#photo' + id).removeClass("active");
    $("#photosContainer").sortable("enable");
}
function savePhoto(id, oldAlbumId) {
    var title = $('#title').val();
    var description = $('#caption').val();
    var dateTaken = $('#dateTaken').val();
    var albumId = $('#albumsCombobox').val();
    $.ajax({
        type: "POST",
        url: "updatePhoto.asp",
        data: { id: id, action: 2, title: title, description: description, albumId: albumId, dateTaken: dateTaken },
        //contentType: "application/json; charset=utf-8",
        dataType: "text",
        error: function(XMLHttpRequest, textStatus, errorThrown) {
            alert(textStatus);
        },
        complete: function(response) {
            cancelEdit(id, title, description, dateTaken);
            $('#info' + id).html(title);
            //if change album
            if (albumId != "") {
                //$('#photo' + id).remove()
                var paramsStr = "tabIndex=1&albumId=" + oldAlbumId;
                window.location.href = $.param.querystring(window.location.href, paramsStr);
            }
        }
    });
}
function deletePhoto(id,imgName, albumId) {
    if (confirm("Do you want to delete this item?")) {
        $.ajax({
            type: "POST",
            url: "updatePhoto.asp",
            data: { id: id, action: 1, imgName: imgName },
            dataType: "text",
            error: function(XMLHttpRequest, textStatus, errorThrown) {
                alert(textStatus);
            },
            complete: function(response) {
                //$('#photo' + id).remove();
                var paramsStr = "tabIndex=1&albumId=" + albumId;
                window.location.href = $.param.querystring(window.location.href, paramsStr);
            }
        });
    }
}
function addAlbum(username) {
    var albumName = $.datepicker.formatDate('DD, MM d, yy', new Date());

    $.ajax({
        type: "POST",
        url: "updateAlbum.asp",
        data: { username: username, action: 2, name: albumName },
        dataType: "text",
        error: function(XMLHttpRequest, textStatus, errorThrown) {
            alert(textStatus);
        },
        complete: function(response) {
            var data = response.responseText.split(';');
            var returnAlbumId = data[0];
            var returnAlbumName = data[1];
            $("#photosContainer").remove();
            newAlbumid = returnAlbumId;
            isCreatingAlbum = true;
            
            openPopup_click('UploaderDiv', 700, returnAlbumId, username, '', returnAlbumName);

            var li = $(document.createElement('li'));
            var div = $(document.createElement('div'));
            var span = $(document.createElement('span'));
            var img = $(document.createElement('img'));
            var onMouseUpEvent = "displayPhotos(" + returnAlbumId + ",'" + username + "','photoDiv','" + returnAlbumName + "');";
            span.attr('id', 'albumInfo' + returnAlbumId);
            span.html(returnAlbumName);
            img.attr('src', 'images/no_photo.jpg')
                .attr('onmouseup', onMouseUpEvent);
            div.append(img);
            li.attr('id', 'album' + returnAlbumId);
            li.append(div).append(span);
            $('#albumsContainer').append(li);
        }
    });
}

function getQueryString(name) {
    name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
    var regexS = "[\\?&]" + name + "=([^&#]*)";
    var regex = new RegExp(regexS);
    var results = regex.exec(window.location.href);
    if (results == null)
        return "";
    else
        return decodeURIComponent(results[1].replace(/\+/g, " "));
}
